//
//  SetRightMenusHandler.swift
//  
//
//  Created by 孙长坦 on 2022/8/31.
//

import Foundation
import WebKit
import LibBase


class SetRightMenusHandler: WebViewHandlerProtocol {
    static var id: String = "setRightMenus"
    
    func handler(_ handler: WebViewHandlerProtocol,
                 webView: WKWebViewEx?,
                 frameInfo: WKFrameInfo,
                 params: [String: Any]?) {
        guard let webView = webView else {
            return
        }
        
        guard let params = params,
              let uuid = params["uuid"] as? String else {
            return
        }
        
        var menuDatas: [MenuData]?
        if let data = params["data"] as? [[String: Any]] {
            menuDatas = data.compactMap {
                var menuData = try? CodableBuilder().createDictionaryDecoder().decode(MenuData.self, from: $0)
                
                menuData?.webView = webView
                if menuData?.children != nil {
                    for i in 0 ..< menuData!.children!.count {
                        menuData!.children![i].webView = webView
                    }
                }
                
                return menuData
            }
        } else {
            menuDatas = nil
        }
        
        webView.delegate?.webView(webView, setRightMenus: menuDatas)
        
        runSuccessCallback(webView: webView,
                           uuid: uuid, code: 0, message: "setRightMenus::ok",
                           data: nil, handlerParams: params)
    }
}
